import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Progress, Tag, Button, Empty, Spin, message } from 'antd';
import { PlayCircleOutlined, ClockCircleOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { courseAPI } from '../../utils/api';

import './index.scss';

const MyCourses = () => {
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    fetchMyCourses();
  }, []);

  const fetchMyCourses = async () => {
    try {
      setLoading(true);
      const response = await courseAPI.getMyCourses();
      setCourses(response.data || []);
    } catch (error) {
      message.error('获取课程列表失败');
      console.error('获取我的课程失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCourseClick = (courseId) => {
    navigate(`/courses/${courseId}`);
  };

  const handleContinueLearning = (courseId) => {
    navigate(`/courses/${courseId}/learn`);
  };

  const formatDuration = (minutes) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`;
  };

  const getProgressColor = (progress) => {
    if (progress >= 80) return '#52c41a';
    if (progress >= 50) return '#faad14';
    return '#ff4d4f';
  };

  if (loading) {
    return (
      <div className="my-courses-loading">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <div className="my-courses">
      <div className="page-header">
        <h1>我的课程</h1>
        <p>继续您的学习之旅</p>
      </div>

      {courses.length === 0 ? (
        <Empty
          description="您还没有购买任何课程"
          className="empty-state"
        >
          <Button type="primary" onClick={() => navigate('/courses')}>
            去课程中心
          </Button>
        </Empty>
      ) : (
        <Row gutter={[24, 24]}>
          {courses.map((course) => (
            <Col xs={24} sm={12} lg={8} xl={6} key={course.id}>
              <Card
                hoverable
                className="course-card"
                cover={
                  <div className="course-cover">
                    <img
                      alt={course.title}
                      src={course.cover || '/default-course-cover.jpg'}
                      onClick={() => handleCourseClick(course.id)}
                    />
                    <div className="course-overlay">
                      <Button
                        type="primary"
                        icon={<PlayCircleOutlined />}
                        onClick={() => handleContinueLearning(course.id)}
                      >
                        继续学习
                      </Button>
                    </div>
                  </div>
                }
                actions={[
                  <Button
                    key="learn"
                    type="link"
                    onClick={() => handleContinueLearning(course.id)}
                  >
                    继续学习
                  </Button>,
                  <Button
                    key="detail"
                    type="link"
                    onClick={() => handleCourseClick(course.id)}
                  >
                    课程详情
                  </Button>
                ]}
              >
                <Card.Meta
                  title={
                    <div className="course-title" onClick={() => handleCourseClick(course.id)}>
                      {course.title}
                    </div>
                  }
                  description={
                    <div className="course-info">
                      <div className="course-teacher">
                        <UserOutlined /> {course.teacher?.nickname || course.teacher?.username}
                      </div>
                      
                      <div className="course-stats">
                        <span>
                          <ClockCircleOutlined /> {formatDuration(course.duration)}
                        </span>
                        <span>{course.lessons_count} 课时</span>
                      </div>

                      <div className="course-progress">
                        <div className="progress-info">
                          <span>学习进度</span>
                          <span>{course.progress || 0}%</span>
                        </div>
                        <Progress
                          percent={course.progress || 0}
                          strokeColor={getProgressColor(course.progress || 0)}
                          showInfo={false}
                          size="small"
                        />
                      </div>

                      <div className="course-status">
                        {course.progress === 100 ? (
                          <Tag color="success">已完成</Tag>
                        ) : course.progress > 0 ? (
                          <Tag color="processing">学习中</Tag>
                        ) : (
                          <Tag color="default">未开始</Tag>
                        )}
                      </div>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
};

export default MyCourses; 